import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { NoticeBar } from "antd-mobile";
import styles from "./Login.module.less";
import logoPic from "@assets/images/logo.png";
import LoginForm from "./LoginForm";
import FirstLoginForm from "./FirstLoginForm";
import { AclApi } from "@api";
import { createAction } from "@common/utils";
import { SET_ERR_MSG } from "@store/global-state/action-types";
import {
  SET_PAGE_STACK,
  SET_LOGIN_RESP,
} from "@store/global-state/action-types";
import ServerIpForm from "./ServerIpForm";

const Login = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const errMsg = useSelector((state) => state.globalState.errMsg);
  const [firstLogin, setFirstLogin] = useState(false);
  const [serverIp, setServerIp] = useState(
    window.localStorage.getItem("SERVER_IP")
  );

  const handleLogin = (formValues) => {
    // if ("cordova" in window) {
      let { account, password } = formValues;
      document.getElementById("load-box").style.visibility = "visible";
      AclApi.initLogin()
        .then((resp) => {
          return resp.data;
        })
        .then((initLoginResp) => {
          let { responseHeader, payload } = initLoginResp;
          return AclApi.login({
            timestamp: responseHeader.timestamp,
            secNonce: payload.secNonce,
            exponent: payload.secParam.exponent,
            modulus: payload.secParam.modulus,
            sessionId: payload.sessionId,
            account,
            password,
          });
        })
        .then((loginResp) => {
          let { user, nonceArr, perms, token } = loginResp.data.payload;
          window.sessionStorage.setItem("nonceArray", nonceArr);
          dispatch(
            createAction(SET_LOGIN_RESP, {
              token,
              perms,
              avatar: user.avatar,
              displayName: user.realName,
            })
          );
          if (user.firstLogin) {
            setFirstLogin(true);
          } else {
            let path = "/app/landing-page/home";
            dispatch(createAction(SET_PAGE_STACK, [path]));
            navigate(path);
          }
          document.getElementById("load-box").style.visibility = "hidden";
          return;
        })
        .catch((err) => {
          console.log(err);
          document.getElementById("load-box").style.visibility = "hidden";
          dispatch(
            createAction(
              SET_ERR_MSG,
              err.response.data.responseHeader.errorMessage
            )
          );
        });
    // } else {
    //   let path = "/app/landing-page/home";
    //   dispatch(createAction(SET_PAGE_STACK, [path]));
    //   navigate(path);
    // }
  };

  const renderForm = () => {
    // return (
    //   <ServerIpForm
    //     handleSaveServerIp={(ip) => {
    //       window.localStorage.setItem("SERVER_IP", ip);
    //       setServerIp(ip);
    //     }}
    //   />
    // );
    if (serverIp) {
      return firstLogin ? (
        <FirstLoginForm />
      ) : (
        <LoginForm handleLogin={handleLogin} />
      );
    } else {
      return (
        <ServerIpForm
          handleSaveServerIp={(ip) => {
            window.localStorage.setItem("SERVER_IP", ip);
            setServerIp(ip);
          }}
        />
      );
    }
  };

  return (
    <div className={styles["bg"]}>
      <div className={styles["container"]}>
        <div className={styles["logo-box"]}>
          <img src={logoPic} />
        </div>
        <NoticeBar
          content={errMsg}
          color="error"
          style={{
            margin: "2rem 0 0",
            visibility: errMsg ? "visible" : "hidden",
          }}
        />
        {renderForm()}
        <div className={styles["version-box"]}>
          <div>&copy; {new Date().getFullYear()} Powered by CONYOU</div>
          <div>Version 2.0.0</div>
        </div>
      </div>
    </div>
  );
};

export default Login;
